using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class SelectColorHelper : NodeHelper
    {
        public Color disableColor = new(255, 255, 255, 0.4f);
        public Color originColor = new(255, 255, 255);
        public Color defaultColor;
        public List<SelectColorItem> list;

        public bool raw;
        public bool text;
        private Image _Image;
        private RawImage _RawImage;
        private Text _Text;

        private Image Image
        {
            get
            {
                if (_Image == null) _Image = GetComponent<Image>();
                return _Image;
            }
        }

        private RawImage RawImage
        {
            get
            {
                if (_RawImage == null) _RawImage = GetComponent<RawImage>();
                return _RawImage;
            }
        }

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        protected override BindDataType bindDataType => BindDataType.String;

        protected override void BindData(string s)
        {
            if (StringTools.IsEmpty(s)) return;
            var color = defaultColor;
            for (var i = 0; i < list.Count; i++)
                if (s == list[i].key)
                {
                    color = list[i].color;
                    break;
                }

            SetColor(color);
        }

        protected override void BindData(bool b)
        {
            if (b)
                Enabled();
            else
                Disabled();
        }

        private void SetColor(Color c)
        {
            if (raw)
                RawImage.color = c;
            else if (text)
                Text.color = c;
            else
                Image.color = c;
        }

        private void Disabled()
        {
            if (raw)
                RawImage.color = disableColor;
            else if (text)
                Text.color = disableColor;
            else
                Image.color = disableColor;
        }

        private void Enabled()
        {
            if (raw)
                RawImage.color = originColor;
            else if (text)
                Text.color = originColor;
            else
                Image.color = originColor;
        }

        [Serializable]
        public class SelectColorItem
        {
            public string key;
            public Color color;
        }
    }
}